import React, { useCallback, useEffect, useMemo, useState } from 'react';
import './Department.scss';
import { fetchDepartmentList } from '@/store/modules/departmentStore';
import { SideBar, Toast } from 'antd-mobile';
import { useEnhanceDispatch, useEnhanceSelector } from '@/hooks';
import NavBar from '@/components/NavBar/NavBar';
import { Link, useNavigate } from 'react-router-dom';
import { setDepId } from '@/store/modules/consultStore';

const Department = () => {
  const enhanceDispatch = useEnhanceDispatch();
  const navigate = useNavigate();
  const departmentList = useEnhanceSelector(state => state.departmentStore.departmentList);
  const [activeKey, setActiveKey] = useState('6976485709309804544');
  const subDepartmentList = useMemo(() => departmentList.find(item => item.id === activeKey), [departmentList, activeKey]);
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>选择科室</span>), []);
  // 右边插槽内容
  const right = useCallback(() => (<Link to="/">问诊记录</Link>), []);

  /**
   * @description 获取科室列表的回调函数
   * */
  const fetchDepartment = async () => {
    try {
      await enhanceDispatch(fetchDepartmentList()).unwrap();
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  /**
   * @description 切换面板的回调
   * */
  const changeSideBar = (key: string) => {
    setActiveKey(key);
  };


  /**
   * @description 第三步：设置科室ID并且跳转到病情描述页面
   * */
  const selectDept = (departmentId: string) => {
    enhanceDispatch(setDepId(departmentId));
    navigate('/consult-illness')
  };

  useEffect(() => {
    fetchDepartment();
  }, []);

  return (
    <div className="department">
      {/*导航栏组件*/}
      <NavBar back={left()} children={children()} right={right()} onBack={() => navigate(-1)}></NavBar>
      <div className="department-list">
        <div className="left">
          <SideBar onChange={changeSideBar} activeKey={activeKey}>
            {departmentList.map(item => (<SideBar.Item key={item.id} title={item.name}></SideBar.Item>))}
          </SideBar>
        </div>
        <div className="right">
          {
            subDepartmentList?.child.map(item => <a onClick={() => selectDept(item.id)} key={item.id}>{item.name}</a>)
          }
        </div>
      </div>
    </div>
  );
};

export default Department;